var monthTable = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 获取目标日期的下一天    
 * 日期格式 YYYY-MM-dd
 * @param {string} curDate 目标日期
 */
const getNextDay = curDate => {
  let f_date = curDate.split ("-")
  if (f_date.length < 3) return curDate
  let year = Number (f_date[0])
  let mon = Number (f_date[1])
  let day = Number (f_date[2])
  if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
    monthTable[2] = 29
  } else {
    monthTable[2] = 28
  }
  if (day + 1 > monthTable[mon]) {
    day = 1
    mon = mon + 1
    if (mon > 12) {
      mon = 1
      year = year + 1
    }
  } else {
    day = day + 1
  }
  return year + '-' + (mon>9?mon:('0'+mon)) + '-' + (day>9?day:('0'+day))
}

/**
 * 获取目标日期的前一天    
 * 日期格式 YYYY-MM-dd
 * @param {string} curDate 目标日期
 */
const getPreDay = curDate => {
  let f_date = curDate.split ("-")
  if (f_date.length < 3) return curDate
  let year = Number (f_date[0])
  let mon = Number (f_date[1])
  let day = Number (f_date[2])
  if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
    monthTable[2] = 29
  } else {
    monthTable[2] = 28
  }
  if (day - 1 < 1) {
    mon = mon - 1
    if (mon < 1) {
      mon = 12
      year = year - 1
    }
    day = monthTable[mon]
  } else {
    day = day - 1
  }
  return year + '-' + (mon>9?mon:('0'+mon)) + '-' + (day>9?day:('0'+day))
}

module.exports = {
  formatTime: formatTime,
  getNextDay: getNextDay,
  getPreDay: getPreDay
}